package org.yiming.tools.mqtt.client;

import lombok.Getter;
import lombok.NoArgsConstructor;
import org.yiming.tools.mqtt.client.client.MqttClient;
import org.yiming.tools.mqtt.client.client.MqttConfigFactory;
import org.yiming.tools.mqtt.client.client.command.*;
import org.yiming.tools.mqtt.client.command.Command;
import org.yiming.tools.mqtt.client.command.CommandDispatcher;
import org.yiming.tools.mqtt.client.command.HelpCommand;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Application容器
 * @author renwenpeng
 * date  2022/3/25 3:39 下午
 */
@NoArgsConstructor
public class ApplicationContext {
    @Getter
    private final ExecutorService threadPoolTaskExecutor = Executors.newScheduledThreadPool(2);
    @Getter
    private final MqttConfigFactory mqttConfigFactory = new MqttConfigFactory();
    @Getter
    private final CommandDispatcher commandDispatcher = new CommandDispatcher(this);

    public void init(){
        initCommand();
    }

    private void initCommand(){
        List<Command> commands = Arrays.asList(new PublishCommand(this)
                , new SubscribeCommand(this)
                , new UnsubscribeCommand(this)
                , new UseMqttClientCommand(this)
                , new ConnCommand(this)
                , new ShowMqttClientCommand(this)
                , new ReconnectCommand(this)
                , new HelpCommand(this));
        commands.forEach(command -> {
            for (String name : command.name()) {
                commandMap.put(name, command);
            }
        });
    }

    private final Map<String, Command> commandMap = new HashMap<>();

    private final Map<String, MqttClient> mqttClientMap = new HashMap<>();

    public Map<String, Command> getCommandMap() {
        return Collections.unmodifiableMap(commandMap);
    }

    public Map<String, MqttClient> getMqttClientMap() {
        return Collections.unmodifiableMap(mqttClientMap);
    }

    public void putMqttClient(MqttClient mqttClient){
        mqttClientMap.put(mqttClient.getName(), mqttClient);
    }
}
